//
//  MNDTenderProjectViewController.m
//  PlusTenderDemo
//
//  Created by Vitas on 2018/7/18.
//  Copyright © 2018年 Bylongma. All rights reserved.
//

#import "MNDTenderProjectViewController.h"
#import "MNDTenderProjectCell.h"
#import "SYRefreshControl.h"
#import "MNDPlusBorrowProjectModel.h"
#import "MNDWebViewController.h"

#define kMNDTenderProjectCell @"MNDTenderProjectCell"

@interface MNDTenderProjectViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic, assign) NSInteger perpage;

@property(nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation MNDTenderProjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    kdeclare_weakself
    [SYRefreshControl configGifMJRefresh:self.tableView
                             refreshType:MJRefreshSupportALl
                            beginRefresh:YES
                         timeLabelHidden:YES
                        stateLabelHidden:YES
                            refreshBlock:^{
                                
                                [weakSelf loadDatas];
                                
                            } loadMoreBlock:^{
                                
                                [weakSelf loadMoreDatas];
                            }];
    
    [weakSelf.tableView configBlankPage:SYBlankPageTypeNoData hasData:weakSelf.dataArray reloadButtonBlock:^(id sender) {
        [weakSelf loadDatas];
    }];
    self.tableView.tableFooterView = [UIView new];
    [self customBackBarButton];
    // Do any additional setup after loading the view.
}

- (void)customBackBarButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
    
}

- (void)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 懒加载
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark - 加载数据
- (void)loadDatas {
    
    kdeclare_weakself;
    self.perpage = 1;
    NSDictionary *params = @{
                             @"perpage": @(self.perpage),
                             @"pagesize": @(10),
                             @"sign_id": self.sign_id
                             };
    [APIManager sendRequestWithURL:API_AUTO_PLUS_BORROW_PROJECT parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakSelf.dataArray = [MNDPlusBorrowProjectModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"user_tender_plan"]];
            [weakSelf.tableView reloadData];
            [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:weakSelf.dataArray.count];
            [weakSelf.view configBlankPage:SYBlankPageTypeNoData hasData:weakSelf.dataArray.count reloadButtonBlock:nil];
        }else {
            [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:NO];
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:NO];
        if (weakSelf.dataArray.count > 0) {
            [NetworkProgressHUD showHudNetworkError:error];
        } else {
            SYBlankPageType blankType = [weakSelf.view blankPageTypeWithError:error];
            [weakSelf.view configBlankPage:blankType
                                   hasData:NO
                         reloadButtonBlock:^(id sender) {
                             [weakSelf loadDatas];
                         }];
        }
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadMoreDatas {
    
    kdeclare_weakself;
    self.perpage ++;
    NSDictionary *params = @{
                             @"perpage": @(self.perpage),
                             @"pagesize":@(10),
                             @"sign_id": self.sign_id
                             };
    [APIManager sendRequestWithURL:API_AUTO_PLUS_BORROW_PROJECT parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            NSArray *array = [MNDPlusBorrowProjectModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"user_tender_plan"]];
            [weakSelf.dataArray addObjectsFromArray:array];
            [weakSelf.tableView reloadData];
            [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:array.count];
            
        }else {
            [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:NO];
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:NO];
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MNDTenderProjectCell *cell = [tableView dequeueReusableCellWithIdentifier:kMNDTenderProjectCell];
    MNDPlusBorrowProjectModel *model = self.dataArray[indexPath.section];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MNDPlusBorrowProjectModel *model = self.dataArray[indexPath.section];
    if (model.is_return.integerValue == 1){
        return;
    }
    
    kdeclare_weakself;
    [NetworkProgressHUD showHud];
        
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"tender_id": model.tender_id, @"operation": @"4"}];
    [APIManager sendRequestWithPath:API_TENDER_PROTOCOL parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
            webVC.webViewUrl = responseModel.data;
            webVC.naviBarHidden = NO;
            webVC.loadType = LoadTypeLink;
            webVC.title = @"借款协议";
            UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:webVC];
            [weakSelf presentViewController:naviVC animated:YES completion:^{
                
            }];
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
            }
        }
        
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 8;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
